<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="description" content="">
  <meta name="keywords" content="">
  
    <link rel="icon" href="/avatar.jpg">
  
    
  <title>解决 Emacs 的 Python 交互执行环境在 windows 下无法显示中文的问题 | 科学君的不科学博客</title>
  <link rel="stylesheet" href="/style.css">
  <link rel="stylesheet" href="/lib/jquery.fancybox.min.css">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <script type="text/javascript" src="https://tajs.qq.com/stats?sId=65546304" charset="UTF-8"></script>
  <script>
  (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
          bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      }
      else {
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>
</head>

<body>
  <header>
  <div class="header-container">
    <a class='logo' href="/">
      <span>科学君的不科学博客</span>
    </a>
    <ul class="right-header">
      
        <li class="nav-item">
          
            <a href="/" class="item-link">首页</a>
          
        </li>
      
        <li class="nav-item">
          
            <a href="/about" class="item-link">关于</a>
          
        </li>
      
        <li class="nav-item">
          
            <a href="/archives" class="item-link">归档</a>
          
        </li>
      
        <li class="nav-item">
          
            <a href="/tags" class="item-link">标签</a>
          
        </li>
      
        <li class="nav-item">
          
            <a href="/atom.xml" class="item-link">FEED 订阅</a>
          
        </li>
      
    </ul>
  </div>
</header>

  <main id='post'>
  <div class="content">
    <article>
      <section class="content markdown-body">
        <h1>解决 Emacs 的 Python 交互执行环境在 windows 下无法显示中文的问题</h1>
        <div class='post-meta'>
          <i class="fa fa-calendar" aria-hidden="true"></i>
          <time>2016年09月29日</time>
          
          | <i class="fa fa-folder-open-o" aria-hidden="true"></i> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/blog/">blog</a>
  </div>



          
          
          |
          
          <i class="fa fa-tags" aria-hidden="true"></i>
          
          
  <a href="/tags/#emacs" class='tag'>emacs</a>

  <a href="/tags/#org" class='tag'>org</a>

  <a href="/tags/#windows" class='tag'>windows</a>


          
        </div>
        <ul>
<li><a href="#sec-">问题描述</a></li>
<li><a href="#sec-">解决方案</a></li>
<li><a href="#sec-">org-babel 的问题</a></li>
<li><a href="#sec-">TIPS</a></li>
<li><a href="#sec-">16/9/30 更新</a></li>
<li><a href="#sec-">16/10/12 更新</a></li>
<li><a href="#sec-">16/12/5 更新</a></li>
</ul>
<h1 id="问题描述"><a href="#问题描述" class="headerlink" title="问题描述"></a>问题描述<a id="sec-"></a></h1><p>我把 Emacs 默认的编码改成了 utf-8，代码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">(set-language-environment &quot;chinese-GBK&quot;)</span><br><span class="line">(prefer-coding-system &apos;utf-8)</span><br></pre></td></tr></table></figure>
<p>由于 windows 中的 shell 默认只支持中文的 gbk 编码，强制修改全部的编码会导致乱码，所以用这种 方法可以得到一个“prefer”的编码系统，在 shell 里面就不会乱码了。但是如果在 shell-mode 下的 python 的交互环境中输入中文却会得到异常，并且交互编程时显示的中文会变成像 <code>\320\320\315\352\261\317</code> 这样的编码形式。</p>
<h1 id="解决方案"><a href="#解决方案" class="headerlink" title="解决方案"></a>解决方案<a id="sec-"></a></h1><p>本来这就是改一下编码就能解决的问题，理论上可以把上面代码第二行的 utf-8 改成 <code>gbk</code> 就可以了。 但是我为了保持文件的兼容性，没法采用这样的配置。只好把 terminal 的编码单独改成 gbk，在 上面的代码下面加上这几行即可：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">(when (spacemacs/system-is-mswindows)</span><br><span class="line">  ;; from http://paxinla.github.io/2015/07/12/Windows%E4%B8%8BEmacs%E7%9A%84shell-mode%E4%B9%B1%E7%A0%81%E8%A7%A3%E5%86%B3/</span><br><span class="line">  ;; 解决 Shell Mode(cmd) 下中文乱码问题</span><br><span class="line">  (set-terminal-coding-system &apos;gbk)</span><br><span class="line">  (modify-coding-system-alist &apos;process &quot;*&quot; &apos;gbk)</span><br><span class="line">  (defun liu233w/windows-shell-mode-coding ()</span><br><span class="line">    (set-buffer-file-coding-system &apos;gbk)</span><br><span class="line">    (set-buffer-process-coding-system &apos;gbk &apos;gbk))</span><br><span class="line">  (add-hook &apos;shell-mode-hook #&apos;liu233w/windows-shell-mode-coding)</span><br><span class="line">  (add-hook &apos;inferior-python-mode-hook #&apos;liu233w/windows-shell-mode-coding)</span><br><span class="line">  )</span><br></pre></td></tr></table></figure>
<p>注意那个 <code>inferior-python-mode-hook</code> ，如果你还有别的交互环境出现了这种问题，可以把相应的 hook 加上这个函数。</p>
<p>这下无论是交互环境还是 shell 都不会出问题了。</p>
<h1 id="org-babel-的问题"><a href="#org-babel-的问题" class="headerlink" title="org-babel 的问题"></a>org-babel 的问题<a id="sec-"></a></h1><p>由于我们将进程编码改的与文件编码不同了，使用 org-babel 的时候返回的内容会在行末多出来一个 <code>^M</code> ，我们还需要用别的代码来处理这个问题。这里的 <code>remove-dos-eol</code> 是我从子龙山人的配置里 抄过来的。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">(defun liu233w/remove-dos-eol ()</span><br><span class="line">  &quot;Replace DOS eolns CR LF with Unix eolns CR&quot;</span><br><span class="line">  (interactive)</span><br><span class="line">  (goto-char (point-min))</span><br><span class="line">  (while (search-forward &quot;\r&quot; nil t) (replace-match &quot;&quot;)))</span><br><span class="line"></span><br><span class="line">;; 如果是 windows，则自动处理 org-babel-eval 的返回值，防止使用 gbk 编码的</span><br><span class="line">;; cmd 返回值行末符号不匹配</span><br><span class="line">(with-eval-after-load &apos;ob-python</span><br><span class="line">  (defun liu233w/fix-org-babel-execute:prog (string)</span><br><span class="line">    (with-temp-buffer</span><br><span class="line">      ;; (message (format &quot;debug %s&quot; string))</span><br><span class="line">      (insert string)</span><br><span class="line">      (liu233w/remove-dos-eol)</span><br><span class="line">      (buffer-string)))</span><br><span class="line">  (advice-add #&apos;org-babel-execute:python :filter-return</span><br><span class="line">              #&apos;liu233w/fix-org-babel-execute:prog))</span><br></pre></td></tr></table></figure>
<h1 id="TIPS"><a href="#TIPS" class="headerlink" title="TIPS"></a>TIPS<a id="sec-"></a></h1><ul>
<li>org-bable 为每种语言单独创建的文件中有一个 <code>org-babel-execute:语言名</code> 函数， 用来执行当前的代码块，这个函数返回一个字符串，即执行的结果。</li>
<li><code>with-temp-buffer</code> 宏可以创建一个临时的 buffer，在执行完 body 之后会将其删除。</li>
<li><code>advice-add</code> 函数的 <code>:filter-return</code> 标签可以将某个函数的返回值在返回调用处之 前交给指定的函数处理。</li>
</ul>
<h1 id="16-9-30-更新"><a href="#16-9-30-更新" class="headerlink" title="16/9/30 更新"></a>16/9/30 更新<a id="sec-"></a></h1><p>今天发现如果需要使用 yapf 的话还需要再加一个 advice</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(advice-add #&apos;py-yapf-buffer :after #&apos;liu233w/remove-dos-eol)</span><br></pre></td></tr></table></figure>
<h1 id="16-10-12-更新"><a href="#16-10-12-更新" class="headerlink" title="16/10/12 更新"></a>16/10/12 更新<a id="sec-"></a></h1><p>发现了更加精简的方法，把下面的代码放进 config 中即可：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">(set-language-environment &quot;UTF-8&quot;)</span><br><span class="line">(prefer-coding-system &apos;utf-8)</span><br><span class="line">(when (spacemacs/system-is-mswindows)</span><br><span class="line">  (set-language-environment &quot;chinese-gbk&quot;)</span><br><span class="line">  (set-default &apos;process-coding-system-alist</span><br><span class="line">               &apos;((&quot;[pP][lL][iI][nN][kK]&quot; gbk-dos . gbk-dos)</span><br><span class="line">                 (&quot;[cC][mM][dD][pP][rR][oO][xX][yY]&quot; gbk-dos . gbk-dos)))</span><br><span class="line">  (defun liu233w//python-encode-in-org-babel-execute (func body params)</span><br><span class="line">    &quot;org-babel 执行代码时不会自动编码文件，这里通过动态作用域覆盖默认选项来编码文件。&quot;</span><br><span class="line">    ;; 此问题的详细信息请参考：https://github.com/Liu233w/.spacemacs.d/issues/6</span><br><span class="line">    (let ((coding-system-for-write &apos;utf-8))</span><br><span class="line">      (funcall func body params)))</span><br><span class="line">  (advice-add #&apos;org-babel-execute:python :around</span><br><span class="line">              #&apos;liu233w//python-encode-in-org-babel-execute))</span><br></pre></td></tr></table></figure>
<p>这段代码的说明参见：<a href="https://github.com/Liu233w/.spacemacs.d/issues/6" target="_blank" rel="noopener">https://github.com/Liu233w/.spacemacs.d/issues/6</a> 今后如果还有 babel 的语言出现类似的问题的话，只需要用 <code>function-add</code> 来用这个函数修改 对应的 <code>org-babel-execute</code> 函数即可。</p>
<p>TIPS:</p>
<ul>
<li><code>edebug</code> 可以 debug elisp, 参见 <a href="https://www.gnu.org/software/emacs/manual/html_node/elisp/Edebug.html" target="_blank" rel="noopener">https://www.gnu.org/software/emacs/manual/html_node/elisp/Edebug.html</a></li>
</ul>
<h1 id="16-12-5-更新"><a href="#16-12-5-更新" class="headerlink" title="16/12/5 更新"></a>16/12/5 更新<a id="sec-"></a></h1><p>其实上面的代码还是有问题的，今天终于把这个问题彻底解决了，代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">;; 设置编码</span><br><span class="line">(cond</span><br><span class="line"> ((eq system-type &apos;windows-nt)          ; 或者 (spacemacs/system-is-mswindows)</span><br><span class="line">  ;;</span><br><span class="line">  (set-language-environment &quot;chinese-gbk&quot;)</span><br><span class="line">  (prefer-coding-system &apos;utf-8)</span><br><span class="line">  (set-terminal-coding-system &apos;gbk)</span><br><span class="line">  ;;</span><br><span class="line">  (modify-coding-system-alist &apos;process &quot;*&quot; &apos;gbk)</span><br><span class="line">  (defun liu233w/windows-shell-mode-coding ()</span><br><span class="line">    (set-buffer-file-coding-system &apos;gbk)</span><br><span class="line">    (set-buffer-process-coding-system &apos;gbk &apos;gbk))</span><br><span class="line">  (add-hook &apos;shell-mode-hook #&apos;liu233w/windows-shell-mode-coding)</span><br><span class="line">  (add-hook &apos;inferior-python-mode-hook #&apos;liu233w/windows-shell-mode-coding)</span><br><span class="line">  ;;</span><br><span class="line">  (defun liu233w//python-encode-in-org-babel-execute (func body params)</span><br><span class="line">    &quot;org-babel 执行代码时不会自动编码文件，这里通过动态作用域覆</span><br><span class="line">盖默认选项来编码文件。&quot;</span><br><span class="line">    ;; 此问题的详细信息请参考：https://github.com/Liu233w/.spacemacs.d/issues/6</span><br><span class="line">    (let ((coding-system-for-write &apos;utf-8))</span><br><span class="line">      (funcall func body params)))</span><br><span class="line">  (advice-add #&apos;org-babel-execute:python :around</span><br><span class="line">              #&apos;liu233w//python-encode-in-org-babel-execute))</span><br><span class="line"> ;; --</span><br><span class="line"> (t</span><br><span class="line">  (set-language-environment &quot;UTF-8&quot;)</span><br><span class="line">  (prefer-coding-system &apos;utf-8)))</span><br></pre></td></tr></table></figure>
<ol>
<li><code>set-language-environment</code> 和 <code>prefer-coding-system</code> 的部分设置会互相覆盖，所 以顺序很重要。</li>
<li>经试验发现（因为我也不知道原理），这里的修改 process 部分的编码和之前的那个 <a href="#org3f91627">简化版</a> 产生的效果还是不一样的，这段代码更好一些。</li>
<li>不再需要 <code>remove-dos-eol</code> 了。</li>
<li>不再需要修改 yapf 的设置了。</li>
<li>不会导致别的地方产生乱码（至少我测试到的是这样）</li>
</ol>
<p>我所有的修改记录都保存在 <a href="https://github.com/Liu233w/.spacemacs.d/issues/6" target="_blank" rel="noopener">https://github.com/Liu233w/.spacemacs.d/issues/6</a> 和 <a href="https://github.com/Liu233w/.spacemacs.d/issues/8" target="_blank" rel="noopener">https://github.com/Liu233w/.spacemacs.d/issues/8</a> 里面了。</p>

      </section>
      <div class="license">
        <a href="http://creativecommons.org/licenses/by-sa/3.0/" rel="license" target="_blank">
          <img src="http://i.creativecommons.org/l/by-sa/3.0/88x31.png" style="border-width:0"
               alt="Creative Commons License" class="center">
        </a>
      </div>
      <p>
        本作品采用
        <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank">
          署名-相同方式共享 4.0 国际
        </a>
        进行许可。欢迎转载、使用、重新发布，但务必保留文章署名
        “不科学的科学君” (Liu233w) 与博客链接：
        <a href="https://liu233w.github.io">https://liu233w.github.io</a>
        ，基于本文修改后的作品务必以相同的许可发布。如有任何疑问，请
        <a href="mailto:wwwlsmcom@outlook.com" target="_blank">与我联系</a>
        。
      </p>
    </article>
    
    <!-- disqus 评论框 start -->
    <div class="comment">
      <div id="disqus_thread" class="disqus-thread">
        <i>加载评论框需要翻墙</i>
      </div>
    </div>
    <!-- disqus 评论框 end -->
    
    
    <!-- livere 评论框 start -->
    <div class="comment">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTE5NS8xMTczMA=="></div>
    </div>
    <!-- livere 评论框 end -->
    
  </div>
  <aside>
    
    <div class="toc-container">
      <h1>目录</h1>
      <div class="content">
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#问题描述"><span class="toc-number">1.</span> <span class="toc-text">问题描述</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#解决方案"><span class="toc-number">2.</span> <span class="toc-text">解决方案</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#org-babel-的问题"><span class="toc-number">3.</span> <span class="toc-text">org-babel 的问题</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#TIPS"><span class="toc-number">4.</span> <span class="toc-text">TIPS</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#16-9-30-更新"><span class="toc-number">5.</span> <span class="toc-text">16/9/30 更新</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#16-10-12-更新"><span class="toc-number">6.</span> <span class="toc-text">16/10/12 更新</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#16-12-5-更新"><span class="toc-number">7.</span> <span class="toc-text">16/12/5 更新</span></a></li></ol>
      </div>
    </div>
    
  </aside>
</main>

<!-- disqus 公共JS代码 -->
<script type="text/javascript">
  /* * * CONFIGURATION VARIABLES * * */
  var disqus_shortname = "liu233w";
  var disqus_identifier = "https://liu233w.github.io/2016/09/29/org-python-windows.org/";
  var disqus_url = "https://liu233w.github.io/2016/09/29/org-python-windows.org/";

  isAgent(getDisqus)

  // determine user agent in China
  function isAgent(cb) {
    var url = '//graph.facebook.com/feed?callback=h';
    var xhr = new XMLHttpRequest();
    var called = false;
    xhr.open('GET', url);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        called = true;
        cb(true);
      }
    };
    xhr.send();
    // timeout 1s, this facebook API is very fast.
    setTimeout(function () {
      if (!called) {
        xhr.abort();
        cb(false)
      }
    }, 1000);
  }

  function getDisqus(isAgent) {
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.async = true
    dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq)
  }
</script>
<!-- disqus 公共JS代码 end -->


<script type="text/javascript">
  (function (d, s) {
    var j, e = d.getElementsByTagName(s)[0];

    if (typeof LivereTower === 'function') {
      return;
    }

    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;

    e.parentNode.insertBefore(j, e);
  })(document, 'script');
</script>


  <footer>
  <div class="copyright">
    <div>
      &copy; 2019 | Powered by <a href="https://hexo.io" target="_blank">Hexo</a>&nbsp
    </div>
    <div>
      Theme by <a href="https://github.com/lewis-geek/hexo-theme-Aath" target="_blank">Aath</a>
    </div>
  </div>
</footer>


<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="/lib/in-view.min.js"></script>
<script src="/lib/lodash.min.js"></script>
<script>
  var isDown = true
  var oldY = 0
  inView.offset(50)

  document.body.addEventListener('touchstart', function(){});
  
  window.addEventListener('scroll', _.throttle(e => {
    var currentY = window.scrollY
    if((oldY - currentY) < 0) {
      isDown = true
    } else {
      isDown = false
    }
    oldY = currentY
  }, 250))

  $("article img").each(function() {
      var strA = "<a data-fancybox='gallery' href='" + this.src + "'></a>";
      $(this).wrapAll(strA);
  });

  $('.toc-link').each(function() {
      var href = $(this).attr("href");
      
      inView(href).on('exit', () => {
        if (isDown) {
          handleActive(href)
        }
      })

      inView(href).on('enter', () => {
        if (!isDown) {
          handleActive(href)
        }
      })

      this.onclick = function(e) {
        var pos = $(href).offset().top - 10;
        $("html,body").animate({scrollTop: pos}, 300);
        setTimeout(() => {
          handleActive(href)
        }, 350)
        return false
      }
  })

  function handleActive(href) {
    document.querySelectorAll('.toc-link').forEach(elm => {
      elm.classList.remove('active')
    })
    document.querySelector(".toc [href='"+ href +"']").classList.add('active')
  }
</script>
<script src="/lib/jquery.fancybox.min.js"></script>

<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

</body>
</html>
